<template>
  <div class="ratingList">
    <div v-if="!isShowDetails">
      <div class="myFixed">
        <PageTitle
          :goBack="false"
          title="评分列表"
          :border="true"
          class="myFixed1"
        />
      </div>
      <div class="myCardCss" style="width: 100%;padding-top: 70px">
        <div class="searchDiv">
          <a-form :model="formData" :hideRequiredMark="true" class="rating-list-form" :layout="'inline'" :rules="rules">
            <a-form-item :name="['times']">
              <a-range-picker v-model:value="formData.times" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD HH:mm:ss" :placeholder="['评分开始时间', '评分结束时间']"
                              :showTime="true" style="width: 300px; margin-left: -8px" @change="searchData" />
            </a-form-item>
            <a-select v-model:value="formData.modelIds" placeholder="评分模型" style="width: 120px" allow-clear @change="searchData">
              <a-select-option v-for="(item, index) in modelList" :key="index" :value="item.id">{{
                  item.name
                }}</a-select-option>
            </a-select>
            <a-form-item>
              <a-input-number id="inputNumber" v-model:value="formData.minScore" :min="0" :max="formData.maxScore" placeholder="最小分数"/>
              至
              <a-input-number id="inputNumber" v-model:value="formData.maxScore" :min="formData.minScore" placeholder="最大分数"/>
            </a-form-item>
            <a-input style="width: 240px; margin-right: 8px" placeholder="请输入供应商名称搜索" allow-clear v-model:value="formData.companyName"
                     @keyup.enter="searchData">
              <template #prefix>
                <SearchOutlined />
              </template>
            </a-input>
            <!-- <a-button type="primary" danger style="float: right" @click="downloadResult"
            >下载供应商评分明细</a-button
          > -->
            <a-button type="primary" danger @click="searchData" style="border-radius: 4px">查询</a-button>
          </a-form>
        </div>
        <a-table :dataSource="dataSource" :columns="columns" :pagination="false" :scroll="{ y: 540 }" @change="handleTableChange">
          <template #index="{ index }">
            <label>{{ pageForm.limit * pageForm.size - pageForm.size + index + 1 }}</label>
          </template>
          <template #companyName="{ record }">
            <a-tooltip placement="topLeft" @click="openDetails(record.companyId)">
              <template #title>
                <span>{{ record.companyName }}</span>
              </template>
              <span style="color:#1473dc;cursor:pointer;">{{ record.companyName }}</span>
            </a-tooltip>
          </template>
          <template #operation="{ record }">
            <!-- <a style="color: #1473dc; margin-right: 12px" @click="viewScoreResult(record)">查看结果</a> -->
            <a style="color: #1473dc" @click="downloadSingle(record)" v-if="record.status == 'SUCCESS'">下载报告</a>
          </template>
        </a-table>
        <!-- 分页 -->
        <div class="pagination-container">
          <!-- 共有多少条 -->
          <div class="total-container">共 <span>{{ pageForm.total }}</span> 条</div>
          <a-pagination v-model:current="pageForm.limit" :total="pageForm.total" :defaultPageSize="pageForm.size" show-less-items
                        :hideOnSinglePage="true" :showSizeChanger="false" @change="changePage" />
        </div>
      </div>
    </div>
    <!-- 评分结果弹窗 -->
    <score-result-dialog v-model:open-status="scoreResultDialog" @ok="scoreResultOk" @update:open-status="scoreResultClose" :pdf-url="pdfUrl" />
    <SupplierDetails v-if="isShowDetails" :company-id="companyId" @go-back="goBack" />
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import PageTitle from '/@/components/PageTitle/index.vue';
import ScoreResultDialog from './components/ScoreResultDialog.vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import SupplierDetails from '/@/components/SupplierDetails/index.vue';
import {
  getModelSelectList,
  getScoreList,
  exportRecord,
  downloadRecordPdfApi,
} from '/@/api/supplierRating';
import { saveAs } from 'file-saver';
import type { Rule } from 'ant-design-vue/es/form';
import type { FormInstance } from 'ant-design-vue';
import {message} from "ant-design-vue";

const rules = ref<Record<string, Rule[]>>({
  times: [
    {
      type: 'array',
      len: 2,
      required: false,
      trigger: ['change', 'blur'],
    },
  ],
});
let formData = ref({
  times: [],
  modelIds: null,
  minScore: null,
  maxScore: null,
  companyName: '',
  field: '', // 排序字段
  order: '', // 排序方式
});
let dataSource = ref([]);
let columns = ref([
  {
    title: '序号',
    align: 'center',
    width: 55,
    slots: { customRender: 'index' },
  },
  {
    title: '供应商名称',
    dataIndex: 'companyName',
    align: 'left',
    ellipsis: true,
    width: 180,
    slots: { customRender: 'companyName' },
  },
  {
    title: '社会统一信用代码',
    dataIndex: 'creditCode',
    key: 'creditCode',
    width: 180,
    align: 'left',
  },
  {
    title: '评分',
    dataIndex: 'score',
    key: 'score',
    width: 60,
    align: 'left',
    sorter: true,
  },
  {
    title: '评分时间',
    dataIndex: 'ratingTime',
    key: 'ratingTime',
    width: 100,
    align: 'left',
  },
  {
    title: '评分模型',
    dataIndex: 'modelName',
    key: 'modelName',
    width: 100,
    align: 'left',
  },
  {
    title: '创建时间',
    dataIndex: 'createDate',
    key: 'createDate',
    width: 174,
    align: 'left',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 160,
    slots: { customRender: 'operation' },
    align: 'center',
    fixed: 'right',
  },
]);
function handleTableChange(pag: any, filters: any, sorter: any) {
  formData.value.field = sorter.field
  formData.value.order = sorter.order === 'ascend' ? 'asc' : sorter.order === 'descend' ? 'desc' : ''
  getList()
}
let modelList = ref<Array<any>>([]); // 模型下拉
async function getBaseList() {
  const res = await getModelSelectList();
  modelList.value = res;
}
getBaseList();
let pageForm = ref({
  size: 10,
  limit: 1,
  total: 0,
});
function changePage(val) {
  pageForm.value.limit = val;
  // todo
  getList();
}
function searchData() {
  pageForm.value.limit = 1;
  getList();
}
async function getList() {
  let queryData = {
    companyName: formData.value.companyName,
    modelIds: formData.value.modelIds,
    minScore: formData.value.minScore,
    maxScore: formData.value.maxScore,
    ratingTimeStart:
      formData.value.times && formData.value.times.length === 2 ? formData.value.times[0] : '',
    ratingTimeEnd:
      formData.value.times && formData.value.times.length === 2 ? formData.value.times[1] : '',
    field: formData.value.order ? formData.value.field : '',
    order: formData.value.order,
    limit: pageForm.value.limit,
    size: pageForm.value.size,
  };
  const res = await getScoreList(queryData);
  dataSource.value = res.list;
  pageForm.value.total = res.total;
}
getList();
// 下载
async function downloadResult() {
  let queryData = {
    companyName: formData.value.companyName,
    modelIds: formData.value.modelIds,
    minScore: formData.value.minScore,
    maxScore: formData.value.maxScore,
    ratingTimeStart:
      formData.value.times && formData.value.times.length === 2 ? formData.value.times[0] : '',
    ratingTimeEnd:
      formData.value.times && formData.value.times.length === 2 ? formData.value.times[1] : '',
  };
  let res = await exportRecord(queryData);
  let url = window.URL.createObjectURL(res.data);
  let link = document.createElement('a');
  link.style.display = 'none';
  link.download = '供应商评分明细.xlsx';
  link.href = url;
  document.body.appendChild(link);
  link.click();
}

// 下载报告
const downloadSingle = async (row: any) => {
  try {
    if (!row.id) return;
    const resultStream = await downloadRecordPdfApi(row.id);
    if (resultStream.data) {
      saveAs(resultStream.data, `${row.companyName}评分报告_${row.createDate}`);
    }
  } catch (error) {
    console.log(error);
  }
};

// 报告结果预览弹窗
const scoreResultDialog = ref<boolean>(false);
// 行数据缓存
const rowTemp = ref(null);
// 当前查看的pdf url地址
const pdfUrl = ref<string>('');
// 查看报告结果 先获取报告链接
async function viewScoreResult(row: any) {
  try {
    if (!row.id) return;
    rowTemp.value = row;
    const resultStream = await downloadRecordPdfApi(row.id);
    if (resultStream.data) {
      const url = URL.createObjectURL(resultStream.data);
      console.log(url, "预览地址");
      pdfUrl.value = url;
      scoreResultDialog.value = true;
    }
  } catch (error) {
    console.log("error", error);
  }
}
// 预览完成
async function scoreResultOk() {
  await downloadSingle(rowTemp.value);
}
function scoreResultClose(flag) {
  scoreResultDialog.value = flag;
  rowTemp.value = null;
  URL.revokeObjectURL(pdfUrl.value);
  pdfUrl.value = '';
}
let isShowDetails = ref(false);
let companyId = ref('');
function openDetails(id: string) {
  if (id === '-') {
    return message.warning('未查到该公司详情');
  }
  companyId.value = id;
  isShowDetails.value = true;
}
function goBack() {
  isShowDetails.value = false;
}
</script>
<style lang="less" scoped>
.ratingList {
  .searchDiv {
    :deep(.rating-list-form) {
      .ant-form-item-explain-connected {
        display: none;
      }
    }

    margin-bottom: 16px;

    .searchBtn {
      float: right;
      border: 1px solid #1473dc;
      width: 88px;
      height: 32px;
      text-align: center;
      line-height: 32px;
      font-size: 14px;
      font-weight: 500;
      color: #1473dc;
      cursor: pointer;
    }
  }

  :deep(.pagination-container) {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 16px;

    .ant-pagination {
      margin-left: 16px;

      .ant-pagination-item {
        border: unset !important;
        height: 32px !important;
        line-height: 32px !important;

        &.ant-pagination-item-active {
          background-color: #fff !important;

          a {
            color: #c11a20 !important;
          }
        }
      }

      .ant-pagination-next,
      .ant-pagination-prev {
        height: 32px !important;
        line-height: 32px !important;
        border: unset !important;

        .ant-pagination-item-link {
          border: unset !important;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }

    .total-container {
      color: #606266;
      font-size: 14px;

      &>span {
        color: #c11a20;
      }
    }
  }
}
.myFixed1 {
  width: calc(100% - 7px);
  z-index: 10;
}
.myFixed {
  position: fixed;
  z-index: 10;
  width: calc(100% - 258px);
  background: #ffffff;
}

.ant-form-inline .ant-form-item {
  margin-right: 8px !important;
}
:deep(.ant-table-column-sorters){
  justify-content: left !important;
}
:deep(.ant-table-column-title){
  flex: unset !important;
}
</style>
